home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / TPTUTR0F.ZIP / PASCAL3.TXT < prev    next >
Text File  |  1995-12-14  |  12KB  |  290 lines

  1.                    Turbo Pascal for DOS Beginning Tutorial
  2.                              by Glenn Grotzinger
  3.              Part 3 -- While and Repeat Loops; Case Statements
  4.             all parts copyright 1995-96 (c) by Glenn Grotzinger.
  5.  
  6.         Hello again.  I haven't gotten much input about continued
  7. interest in this tutorial.  I may discontinue it if the interest
  8. doesn't pick up. I am planning on taking this tutorial through all
  9. of the Pascal data structures, and maybe special topics (advanced
  10. ones, too, listen up self-professed Pascal experts -- you may even
  11. learn something. :>).  I haven't gotten any suggestions on the special
  12. topics!!!  Please give comments to ggrotz@2sprint.net.
  13.  
  14. An example of a solution of last week's programming problem:
  15.  
  16. program part2;
  17.  
  18.   { This program accompanies part 2.  It is a program designed to take a
  19.     number representing the dimensions of a multiplication table from the
  20.     user, and then write a multiplication table out to the screen. }
  21.  
  22.   var
  23.     dimension: integer;
  24.     i, j: integer;
  25.  
  26.   begin { part 2 }
  27.  
  28.     {take input for the dimension}
  29.     write('What dimension number do you want for a table? ');
  30.     readln(dimension);
  31.     writeln;
  32.  
  33.     { if dimension not greater than 15, process table }
  34.     if dimension <= 15 then
  35.       begin
  36.  
  37.         { write top line of table }
  38.         write('   ');
  39.         for i := 1 to dimension do
  40.           write(i:4);
  41.         writeln;
  42.  
  43.         { write top rule line }
  44.         write(#201:3);
  45.         for i := 1 to (dimension * 4) do
  46.           write(#205);
  47.         writeln;
  48.  
  49.         { write rest of table }
  50.         for i := 1 to dimension do
  51.           begin
  52.             if i < 10 then
  53.               write(' ');
  54.             write(i,#186);
  55.             for j := 1 to dimension do
  56.               write(i*j :4);
  57.             writeln;
  58.           end;
  59.       end
  60.  
  61.     { else it's greater than 15, write an error message }
  62.     else
  63.       writeln('You must give a dimension that''s 15 or lower.');
  64.   end.
  65.  
  66. If there are any questions as to understanding, or difficulties
  67. in solving the practice problems I pose (only way to improve your
  68. own programming talent is to practice...), write ggrotz@2sprint.net.
  69.  
  70. On to the new stuff....
  71.  
  72. WHILE loops
  73. ===========
  74.         It is possible to have a loop to perform a set of
  75. commands a non-set number of times, until a condition is met.  It
  76. can be a contrived one (we can code the basic idea of a FOR loop
  77. using a while loop or the repeat loop. We see this in the recode
  78. of tutorial6 from last time I will make using a while loop instead
  79. of a for loop.
  80.  
  81. program tutorial7;
  82.   var
  83.     i: integer;
  84.   begin
  85.     writeln('I''m going to write something 10 times.');
  86.     i := 1;
  87.     while i <= 10 do
  88.       begin
  89.         writeln('something', '(Time #':15, i, ')');
  90.         i := i + 1;
  91.       end;
  92.   end.
  93.  
  94. As we see when we run this program, it produces the same output
  95. as program tutorial6 did.  The statements in the while loop
  96. function while the condition is true.  When i becomes 11, the loop
  97. breaks off and the program ends. Like the IF statements, we can
  98. place multiple conditions by connecting them like before with the
  99. AND or OR identifiers...
  100.  
  101. REPEAT loops
  102. ============
  103.         This is another loop we can use.  The WHILE loop will
  104. function while a condition is true. The REPEAT loop stops fun-
  105. ctioning when a condition is true. We see the idea of this again,
  106. when we reconstruct program tutorial6 using the repeat loop...
  107.  
  108. program tutorial8;
  109.   var
  110.     i: integer;
  111.   begin
  112.     writeln('I''m going to write something 10 times.');
  113.     i := 1;
  114.     repeat
  115.       writeln('something', '(Time #':15, i, ')');
  116.       i := i + 1;
  117.     until i > 10;
  118.   end.
  119.  
  120. The programs tutorial6, tutorial7, and tutorial8 perform the same
  121. things, with loops, using different ideas.  The difference of the
  122. while and repeat loops over the for loop is that UNDER NO CIRCUM-
  123. STANCES IS THE INDEX VARIABLE FOR A FOR LOOP TO BE CHANGED WHILE
  124. INSIDE THE LOOP. The conditional variable for a while or repeat
  125. loop can be easily changed as we saw in tutorial7 and tutorial8.
  126. There are many choices and options we can implement with the while
  127. and repeat loops. Menu systems are often implemented like this
  128. Continue until user wants to quit. is the basic logic.).
  129.  
  130. CASE statement
  131. ==============
  132.         As we saw in tutorial5, we may want to make a choice based
  133. on many, multiple options.  This statement is analogous to a series
  134. of IF statements on the same variable.  The CASE statement reduces
  135. the wordiness of such a construct, and makes things easier.  I was
  136. eluding to this statement before when I mentioned then that there
  137. is a better way of doing it.  Well, here it is.  We use the example
  138. of tutorial9 below, which is a rewrite of tutorial5, to illustrate
  139. the use and syntax of a case statement.  Keep in mind that the operator
  140. we use in the case statement (like option below) must be a character
  141. or an integer...
  142.  
  143. program tutorial9;
  144.   var
  145.     one, two: integer;
  146.     option: char;
  147.   begin
  148.     writeln('Enter an integer.');
  149.     readln(one);
  150.     writeln('Enter another integer.');
  151.     readln(two);
  152.     writeln('Use a mathematical symbol to indicate what you want to do');
  153.     writeln('with these two numbers.');
  154.     readln(option);
  155.     case option of
  156.       '+': begin   { sub procedures can be coded as well }
  157.              writeln(one, ' + ', two, ' = ', one + two, '.');
  158.              writeln('See, I can add.');
  159.            end
  160.       '-': writeln(one, ' - ', two, ' = ', one - two, '.');
  161.       '*': writeln(one, ' * ', two, ' = ', one * two, '.');
  162.       '/': writeln(one, ' / ', two, ' = ', one / two :0:3, '.');
  163.     else {catch rest}
  164.       writeln('Use +, -, *, or / as your operator.  Try again.');
  165.     end; {case includes an implied begin.  We MUST end. }
  166.   end.
  167.  
  168. As I said in the note, case statements include an implied BEGIN.  We must
  169. say end; to complete the case statement.  The case statement is formatted
  170. for each of our choices above, and the else can be used as a catch-all in
  171. case the user places something in there that we don't account for in the
  172. program, so we can write an error message to the user.  The syntax of the
  173. case statement is basically as above.  You see everything that can be done
  174. with the case statement under Pascal.
  175.  
  176. Random and Randomize
  177. ====================
  178.         We can generate random numbers by doing the following.
  179. At the beginning of the program, call randomize.  Then do
  180. random(<a number>).  What will happen is it will produce an
  181. integer from 0 and less than the number you put in.  Random(3)
  182. will produce a random number from 0-2.  Example.
  183.  
  184. program tutorial10;
  185.   { write 10 random numbers between 1 and 20 }
  186.   var
  187.     number: integer;
  188.     i: integer;
  189.   begin
  190.     randomize;
  191.     { start the random number generator.  Only call once, but must call! }
  192.     for i := 1 to 10 do
  193.       writeln('Random number (#', i,') = ', random(20) + 1);
  194.       { produce random number from 1-20 instead of 0-19 like random(20) only
  195.         does }
  196.   end.
  197.  
  198. The Upcase and Length Functions, addressing strings
  199. ====================================================
  200.  
  201.         upcase(char) command will place a letter into uppercase.  This
  202. command is useful for input prompts where the user is asked to give input
  203. that involves a character or a string.  To illustrate the use of this
  204. command, which may be placed in a write statement, or an assign (it is
  205. what is defined as a function.  We will see what that is next time.).
  206. write(upcase('c'));  will produce a C on the screen.  Another example,
  207. which uppercases a string.  We use the function length(string) which is
  208. useful for that purpose.  Given a string into that function, it will
  209. return an integer length of the string.
  210.  
  211.      for i := 1 to length(inputstring) do
  212.        upcasestring := upcasestring + upcase(inputstring[i]);
  213.  
  214. This for loop will accomplish it.  The thing we see also, with the illus-
  215. trations of the upcase and length functions, is that we can address any
  216. part of the string by stringname[position in string].  For example, the
  217. string "Charleston" can be there as inputstring.  If we wanted the 5th
  218. character of the string, we say inputstring[5].  inputstring[5] would
  219. be equal to 'l', since it's the 5th character of the string.
  220.  
  221. Programming Practice Problem Notes
  222. ==================================
  223.         I am beginning to see the problems get more difficult as there are
  224. more things we know, and we can do more useful and fun things with our
  225. coding.  You may even want to start setting out and solving simple
  226. mathematical problems for homework, or coding up a simple program that can
  227. figure up your checkbook ... it can be done with what you know now, believe
  228. it or not.  Think about what you can do with your new found knowledge.  Do
  229. not try and overextend yourself trying to do things you have no knowledge of
  230. as of yet.  Attempt this practice programming problem as you hopefully have
  231. the others.  It's a rather fun one, as it's an actual game.  We see we are
  232. coming far and there is a lot farther road to go.  There's lots more
  233. concepts we have to learn, which will enable us to do a whole lot more.
  234. Look forward to several more parts, hopefully...
  235.  
  236. Practice Programming Problem #3
  237. ===============================
  238.         Create a program in Pascal and entirely Pascal that will enable the
  239. user to play a guessing game using the keyboard and the monitor as input and
  240. output.  The points to be addressed in programming this game:
  241.  
  242. 1) The number range of the guessing game must be from 1 to 100.
  243. 2) The user must be given 6 opportunities to guess the number.
  244. 3) After the user guesses at the number, the program is to answer the
  245.    user by saying whether their guess was high or low and tell them the
  246.    number of guesses they have remaining.
  247. 4) If they guess the correct number, give them a congrats message.  If
  248.    they exhaust their attempts, give them a try again message, revealing
  249.    the correct number.
  250. 5) Give them the opportunity to play again by asking whether they want to
  251.    play again (Give them a Y/N prompt.).  Be sure to take care of all 4
  252.    variants of this choice by using the most efficient method you have
  253.    available to you.
  254. 6) Remember as always to code as efficiently as possible.  This one can
  255.    be printed out on one page (38 lines to be exact for my sample of this
  256.    one).  Use that as a coding goal for your learning.
  257. 7) If you get stuck, e-mail me about it, and I'll see if I can help.  Have
  258.    faith.  You have the ability to do it.
  259.  
  260. sample output
  261. -------------------------------------------------------------------------
  262. I'm thinking of a number between 1 and 100.  What is it?
  263. 50
  264. It's higher. (5 guesses remaining)
  265. 75
  266. It's lower.  (4 guesses remaining)
  267. 63
  268. It's higher. (3 guesses remaining)
  269.  
  270. If right:
  271. Congratulations!  You got the number right!
  272.  
  273. If wrong:
  274. Sorry, you ran out of choices.  The number I was thinking of is 68.
  275.  
  276. Play again:
  277. Do you want to play again? (Y/N)
  278. -------------------------------------------------------------------------
  279.  
  280. The right / wrong / play again messages are not statically required.  I am
  281. only giving examples of what they may be.  Your goal for this game should
  282. be to program it so it is playable and user-friendly.  I recommend you to
  283. use the prompt structure right above, though.
  284.  
  285. Next Time
  286. =========
  287. We will discuss functions and procedures and their use next time.  Please
  288. refer your comments to ggrotz@2sprint.net.
  289.  
  290.